# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import threading


class JsonConf(object):
    def __init__(self, file_name):
        self.file_name = file_name
        self._data = self.load_file(file_name)

    def get(self):
        return self._data

    def load_file(self, file_name):
        if not os.path.exists(file_name):
            with open(file_name, 'w', encoding="utf-8") as json_file:
                pass
        with open(file_name, encoding="utf-8") as json_file:
            try:
                data = json.load(json_file)
            except Exception as e:
                print(e)
                data = {}

        return data


class ConfigMgr(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(ConfigMgr, "_instance"):
            with ConfigMgr._instance_lock:
                if not hasattr(ConfigMgr, "_instance"):
                    ConfigMgr._instance = object.__new__(cls)
                    ConfigMgr._instance.load_conf()

        return ConfigMgr._instance

    def load_conf(self):
        #a0 = JsonConf("../../../etc/global_config.json")
        a = JsonConf("../../etc/config.json")
        b = JsonConf("../etc/config.json")
        # 不能放在init中，原因是每调用一次ConfigMgr._instance就会调用一次init
        #tmp = dict(a0.get(), **a.get())
        self._data = dict(a.get(), **b.get())
        #print(self._data)

    @staticmethod
    def get(*args):
        length = len(args)
        if length == 1:
            return ConfigMgr._instance._data[args[0]]
        elif length == 2:
            return ConfigMgr._instance._data[args[0]][args[1]]
        elif length == 3:
            return ConfigMgr._instance._data[args[0]][args[1]][args[2]]


ConfigMgr()

if __name__ == "__main__":
    print(ConfigMgr.get("hqdb"))